# -*- coding: utf-8 -*-
"""
@File    :   run.py
@Author  :   jk.dong
@Desc    :   程序执行入口
    命令行参数-process
    --send 执行发送服务
    --recv 执行接收服务
"""
import click
import time


__SendVersion__ = '1.1.0'
__ReceiveVersion__ = '2.2.1'


@click.command()
@click.argument('process')
def run(process: str):
    from docwork.logger import my_timed_rotating_file_handler
    if process == 'send':
        logging = my_timed_rotating_file_handler('send')
        logging.info(f"********************** Send Service --Version:{__SendVersion__}-- *****************************")
        from docwork.config import RUN_CONF
        from docwork.service.send_service import send_service_work
        run_send = RUN_CONF["run-setting"].get("run_send")
        if not run_send:
            logging.warning(f"发送服务启动失败! 配置项run_send为{run_send}")
            return
        while run_send:
            send_service_work()
            time.sleep(int(RUN_CONF["run-setting"].get("send_sleep_time")))
    elif process == 'recv':
        logging = my_timed_rotating_file_handler('recv')
        logging.info(f"********************** Receive Service --Version:{__ReceiveVersion__}-- *****************************")
        from docwork.config import RUN_CONF
        from docwork.service.receive_service import receive_service_work, get_threads
        run_recv = RUN_CONF["run-setting"].get("run_recv")
        if not run_recv:
            logging.warning(f"接收服务启动失败! 配置项run_recv为{run_recv}")
            return
        thread_list = get_threads()
        if RUN_CONF['run-setting'].get('multiprocess_recv'):
            logging.info("启用多进程接收服务")
            import multiprocessing
            while run_recv:
                with multiprocessing.Pool(2) as pool:
                    # 异步提交任务到进程池
                    async_results = [pool.apply_async(func=receive_service_work, args=(t_id,)) for t_id in thread_list]
                    # 等待所有任务完成并收集结果
                    results = [res.get() for res in async_results]
                    # 输出多进程的运行结果
                    for result in results:
                        logging.info(result)
                time.sleep(int(RUN_CONF["run-setting"].get("recv_sleep_time")))
        else:
            while run_recv:
                for t_id in thread_list:
                    receive_service_work(thread_id=t_id)
                    time.sleep(int(RUN_CONF["run-setting"].get("recv_sleep_time")))


if __name__ == "__main__":
    run()
